package org.jeecg.modules.yc.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.yc.util.DateTimeUtils;
import org.jeecg.modules.yc.web.entity.PdDevice;
import org.jeecg.modules.yc.web.entity.Terminal;
import org.jeecg.modules.yc.web.entity.YcAlarmReport;
import org.jeecg.modules.yc.web.entity.YcTerminalOnlineRate;
import org.jeecg.modules.yc.web.entity.vo.JiMuBi;
import org.jeecg.modules.yc.web.entity.vo.JiMuBiOnlineRate;
import org.jeecg.modules.yc.web.entity.vo.RecordCount;
import org.jeecg.modules.yc.web.service.IPdDeviceService;
import org.jeecg.modules.yc.web.service.ITerminalService;
import org.jeecg.modules.yc.web.service.IYcAlarmReportService;
import org.jeecg.modules.yc.web.service.IYcTerminalOnlineRateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags="局放大屏数据接口")
@RestController
@RequestMapping("/yc/web/jiMuBi")
@Slf4j
public class JiMuBiController {

    @Autowired
    private ITerminalService terminalService;

    @Autowired
    private IPdDeviceService pdDeviceService;

    @Autowired
    private IYcAlarmReportService ycAlarmReportService;

    @Autowired
    private IYcTerminalOnlineRateService ycTerminalOnlineRateService;


    @GetMapping(value = "/terminalOnlineCount")
    public Map<String,Long> terminalOnlineCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算 2 小时前的时间
        LocalDateTime twoHoursAgo = now.minus(2, ChronoUnit.HOURS);

        // 创建 QueryWrapper 对象
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 添加条件：createTime 大于等于 2 小时前的时间
        queryWrapper.ge("last_connect_time", twoHoursAgo);
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",terminalService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/terminalCount")
    public Map<String,Long> terminalCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 创建 QueryWrapper 对象
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",terminalService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/deviceCount")
    public Map<String,Long> deviceCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 创建 QueryWrapper 对象
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",pdDeviceService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/deviceOnlineCount")
    public Map<String,Long> deviceOnlineCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 计算 2 小时前的时间
        LocalDateTime twoHoursAgo = now.minus(2, ChronoUnit.HOURS);
        // 创建 QueryWrapper 对象
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("communication_time",twoHoursAgo);
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",pdDeviceService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/weekAlarmReportCount")
    public Map<String,Long> weekAlarmReportCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取本周的开始时间（周一的 00:00:00）
        LocalDate now = LocalDate.now();
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDateTime startDateTime = startOfWeek.atStartOfDay();

        // 获取本周的结束时间（周日的 23:59:59）
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        LocalDateTime endDateTime = endOfWeek.atTime(LocalTime.MAX);

        // 创建 QueryWrapper 对象，指定泛型类型为 Terminal
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 添加条件：last_connect_time 在本周的时间区间内
        queryWrapper.between("create_time", startDateTime, endDateTime);
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",ycAlarmReportService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/dayAlarmReportCount")
    public Map<String,Long> dayAlarmReportCount(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当天的日期
        LocalDate today = LocalDate.now();
        // 获取当天的开始时间（00:00:00）
        LocalDateTime startOfDay = today.atStartOfDay();
        // 获取当天的结束时间（23:59:59）
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 创建 QueryWrapper 对象，指定泛型类型为 Terminal
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 添加条件：last_connect_time 在当天的时间区间内
        queryWrapper.between("create_time", startOfDay, endOfDay);
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        Map<String,Long> map = new HashMap<>();
        map.put("value",ycAlarmReportService.count(queryWrapper));
        return map;
    }

    @GetMapping(value = "/onlineRate")
    public List<JiMuBiOnlineRate> onlineRate(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前时间（默认时区）
        LocalDateTime currentTime = LocalDateTime.now();
        // 往前推24小时
        LocalDateTime time24HoursAgo = currentTime.minusHours(24);
        // 创建 QueryWrapper 对象，指定泛型类型为 Terminal
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 添加条件：last_connect_time 在当天的时间区间内
        queryWrapper.ge("create_time",time24HoursAgo);
        queryWrapper.eq("sys_org_code",sysUser.getOrgCode());
        List<YcTerminalOnlineRate> ycTerminalOnlineRates = ycTerminalOnlineRateService.list(queryWrapper);
        List<JiMuBiOnlineRate> jiMuBiOnlineRatesT = Lists.newArrayList();
        List<JiMuBiOnlineRate> jiMuBiOnlineRatesD = Lists.newArrayList();
        for(YcTerminalOnlineRate ycTerminalOnlineRate : ycTerminalOnlineRates){
            Date inputTime = ycTerminalOnlineRate.getCreateTime();
            // 格式化 LocalTime 对象为 HH:mm 格式的字符串
            String outputTime = DateTimeUtils.dateToTime(inputTime,"HH:mm");
            JiMuBiOnlineRate jiMuBiOnlineRate = new JiMuBiOnlineRate();
            jiMuBiOnlineRate.setName(outputTime);
            jiMuBiOnlineRate.setType(ycTerminalOnlineRate.getDeviceType());
            jiMuBiOnlineRate.setValue(ycTerminalOnlineRate.getOnlineRate());
            if(ycTerminalOnlineRate.getDeviceType().equals(YcTerminalOnlineRate.DEVICE)){
                jiMuBiOnlineRatesD.add(jiMuBiOnlineRate);
            }else {
                jiMuBiOnlineRatesT.add(jiMuBiOnlineRate);
            }

        }
        jiMuBiOnlineRatesT.addAll(jiMuBiOnlineRatesD);
        return jiMuBiOnlineRatesT;
    }
    @GetMapping(value = "/alarmReport")
    public List<String[]> alarmReport(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取本周的开始时间（周一的 00:00:00）
        LocalDate now = LocalDate.now();
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDateTime startDateTime = startOfWeek.atStartOfDay();

        // 获取本周的结束时间（周日的 23:59:59）
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        LocalDateTime endDateTime = endOfWeek.atTime(LocalTime.MAX);

        // 创建 QueryWrapper 对象，指定泛型类型为 Terminal
        QueryWrapper queryWrapper = new QueryWrapper<>();
        // 添加条件：last_connect_time 在本周的时间区间内
        queryWrapper.between("create_time", startDateTime, endDateTime);
        queryWrapper.likeLeft("sys_org_code",sysUser.getOrgCode());
        List<YcAlarmReport> alarmList =  ycAlarmReportService.list(queryWrapper);
        List<String[]> msgList = Lists.newArrayList();
        for (YcAlarmReport ycAlarmReport : alarmList ){
            msgList.add(new String[]{ycAlarmReport.getAlarmMsg()});
        }
        return msgList;
    }
    /**
     * 大屏折线图
     *
     * @return
     */
    //@AutoLog(value = "报警记录-通过id查询")
    @ApiOperation(value="查询监控折线的数据", notes="查询监控折线的数据")
    @GetMapping(value = "/juMuBiAlarmCountWithTime")
    public JiMuBiOnlineRate[] juMuBiAlarmCountWithTime() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<RecordCount> resultList = ycAlarmReportService.recordCountWithTime(sysUser.getOrgCode());
        int size = resultList.size();
        JiMuBiOnlineRate[] jiMuBiOnlineRates = new JiMuBiOnlineRate[size];
        for (int i = 0; i < size; i++) {
            RecordCount row = resultList.get(i);
            JiMuBiOnlineRate jiMuBiOnlineRate = new JiMuBiOnlineRate();
            jiMuBiOnlineRate.setValue(row.getCount());
            jiMuBiOnlineRate.setName(DateTimeUtils.dateToTime(row.getDate(),"MM-dd"));
            jiMuBiOnlineRates[i] = jiMuBiOnlineRate;
        }
        return jiMuBiOnlineRates;
    }

    /**
     * 获取传感器列表
     *
     * @return
     */
    //@AutoLog(value = "报警记录-通过id查询")
    @ApiOperation(value="获取传感器列表", notes="获取传感器列表")
    @GetMapping(value = "/juMuBiDeviceList")
    public List<PdDevice> juMuBiDeviceList() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<PdDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sys_org_code",sysUser.getOrgCode());
        queryWrapper.last("LIMIT 200");
        List<PdDevice> pdDevices = pdDeviceService.list(queryWrapper);
        return pdDevices;
    }
}